package com.mission.schedule.CommonDialog;

import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.my160920.widget.EditTextC;
import com.mission.schedule.sinaadd.BaseDialog;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.util.Date;
import java.util.Map;

/**
 * 日程内容编辑对话框
 * Created by liwei on 2017/4/18.
 */

public class CalenderEditContentDialog extends Dialog {


    CallBack callBack;

    SharedPrefUtil sharedPrefUtil = null;
    Context context;
    WindowManager windowManager;
    EditText addeverytask_tv;
    Map<String, String> map;
    InputMethodManager imm;
    View view;


    public CalenderEditContentDialog(@NonNull final Context context, @StyleRes int themeResId, WindowManager windowManager, final Map<String, String> map) {
        super(context, themeResId);
        this.context = context;
        this.windowManager = windowManager;
        this.map = map;

        setCanceledOnTouchOutside(true);

        view = LayoutInflater.from(context).inflate(R.layout.dialog_edit, null);
        setContentView(view);

        imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        addeverytask_tv = (EditText) view.findViewById(R.id.schcontent_et);
        if (!map.get(ScheduleTable.schSourceDesc).isEmpty() && !map.get(ScheduleTable.schTags).isEmpty()){
            addeverytask_tv.setText(map.get(ScheduleTable.schTags));
            addeverytask_tv.setSelection(map.get(ScheduleTable.schTags).length());
        }else {
            addeverytask_tv.setText(map.get(ScheduleTable.schContent));
            addeverytask_tv.setSelection(map.get(ScheduleTable.schContent).length());
        }

        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        imm.showSoftInput(addeverytask_tv, 0);

    }

    void save(){
        String content;
        if (!map.get(ScheduleTable.schSourceDesc).isEmpty() && !map.get(ScheduleTable.schTags).isEmpty()) {
            content = addeverytask_tv.getText().toString();
            try {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                App.getDBcApplication().updateUpdateSchschTags(content, map.get(ScheduleTable.schID));

                QueryAlarmData.writeAlarm(context.getApplicationContext());

                Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                Bundle extras = new Bundle();
                intentappwidget.putExtras(extras);
                context.sendBroadcast(intentappwidget);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }else {

            if (addeverytask_tv.getText().toString().isEmpty()) {
                content = "提醒事项";
            } else {
                content = addeverytask_tv.getText().toString();
            }
            try {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                App.getDBcApplication().updateUpdateSchContent(content, map.get(ScheduleTable.schID));
                if (!map.get(ScheduleTable.schRepeatID).equals("0")
                        && !map.get(ScheduleTable.schRepeatID).equals("")
                        && map.get(ScheduleTable.schRepeatID) != null) {
                    App.getDBcApplication().updateSchuledRepeatTo(map.get(ScheduleTable.schRepeatID));
                }
                QueryAlarmData.writeAlarm(context.getApplicationContext());

                Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                Bundle extras = new Bundle();
                intentappwidget.putExtras(extras);
                context.sendBroadcast(intentappwidget);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        callBack.reminderEditTime();
        dismiss();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /* 触摸外部弹窗 */
        if (isOutOfBounds(getContext(), event)) {
            save();
            return false;
        }
        return super.onTouchEvent(event);
    }

    private boolean isOutOfBounds(Context context, MotionEvent event) {
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
        final View decorView = getWindow().getDecorView();
        return (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop))
                || (y > (decorView.getHeight() + slop));
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        params.width = windowManager.getDefaultDisplay().getWidth() - 30;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    public interface CallBack {
        void reminderEditTime();
    }

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }
}
